﻿using System;
using System.Text;
using System.Collections;
using System.Xml;
using InfoJetSoft.Service.Entity;
using System.Net;
using System.IO;
using System.Web;

namespace InfoJetSoft.Service.Util
{
	
	class FormUtil
	{
		
		public static string getParameter(System.Collections.Hashtable paramTable, string key)
		{
			string value_Renamed = (string) paramTable[key];
			if (value_Renamed == null)
			{
				throw new InfoJetException("No parameter " + key, "FU01");
			}
			return value_Renamed;
		}
		
		public static XmlElement createHiddenInput(XmlDocument doc, string name, string value_Renamed)
		{
			XmlElement hiddenInput = doc.CreateElement("input");
			hiddenInput.SetAttribute("type", "hidden");
			hiddenInput.SetAttribute("id", name);
			hiddenInput.SetAttribute("name", name);
			hiddenInput.SetAttribute("value", value_Renamed);
			return hiddenInput;
		}

		//CID 0331 //2009.07.22 //Begin
		public static XmlElement createHiddenTextArea(XmlDocument doc, string name, string value_Renamed)
		{
			XmlElement hiddenTextArea = doc.CreateElement("textarea");
			hiddenTextArea.SetAttribute("style", "display:none;");
			hiddenTextArea.SetAttribute("id", name);
			hiddenTextArea.SetAttribute("name", name);
			if( value_Renamed.Length > 0 )
			{
				hiddenTextArea.InnerXml = value_Renamed;
			}
			else
			{
				hiddenTextArea.InnerText = value_Renamed;
			}
			return hiddenTextArea;
		}
		//CID 0331 //2009.07.22 //End

		public static XmlElement createHiddenDiv(XmlDocument doc, string name, string value_Renamed)
		{
			XmlElement hiddenDiv = (XmlElement) doc.CreateElement("div");
			hiddenDiv.SetAttribute("id", name);
			hiddenDiv.SetAttribute("style", "display:none;");
			hiddenDiv.InnerText = value_Renamed;
			return hiddenDiv;
		}

		public static XmlElement createHiddenDiv(XmlDocument doc, string name)
		{
			XmlElement hiddenDiv = (XmlElement) doc.CreateElement("div");
			hiddenDiv.SetAttribute("id", name);
			hiddenDiv.SetAttribute("style", "display:none;");
			return hiddenDiv;
		}

		public static XmlElement createHiddenDiv(XmlDocument doc)
		{
			XmlElement hiddenDiv = (XmlElement) doc.CreateElement("div");
			hiddenDiv.SetAttribute("style", "display:none;");
			return hiddenDiv;
		}

		public static XmlElement createHiddenA(XmlDocument doc, string name)
		{
			XmlElement hiddenA = (XmlElement) doc.CreateElement("a");
			hiddenA.SetAttribute("id", name);
			hiddenA.SetAttribute("style", "display:none;");
			return hiddenA;
		}

		public static XmlElement createHiddenTable(XmlDocument doc, string name)
		{
			XmlElement hiddenA = (XmlElement) doc.CreateElement("table");
			hiddenA.SetAttribute("id", name);
			hiddenA.SetAttribute("style", "display:none;");
			return hiddenA;
		}
		
		public static string buildListValue(ArrayList valueList)
		{
			StringBuilder valueBuffer = new StringBuilder();
			for (int i = 0; i < valueList.Count; i++)
			{
				string value_Renamed = (string) valueList[ i ];
				valueBuffer.Append(value_Renamed);
				if (i < valueList.Count - 1)
				{
					valueBuffer.Append(JetConstant.ID_SEPARATOR);
				}
			}
			return valueBuffer.ToString();
		}

		public static void addModalMessage( Form form, string prefix, Exception e, bool isSoap )
		{
			string message = prefix + ":\n" + e.Message;
			if( e is System.Net.WebException && isSoap )
			{
				WebException webException = (WebException)e;
				//CID 0145 //2008.10.19 //Begin
				if( webException.Status.Equals( WebExceptionStatus.ProtocolError ) && webException.Message.IndexOf( "401" ) > 0 )
				{
					if( ConfigUtil.HideWS401Message() )
					{
						return;
					}
				}
				//CID 0145 //2008.10.19 //End
				else if( webException.Response != null )
				{
					StreamReader reader = new StreamReader( webException.Response.GetResponseStream(), System.Text.Encoding.UTF8 );
					string xml = reader.ReadToEnd();
					reader.Close();
					XmlDocument soapDoc = new XmlDocument();
					try
					{
						soapDoc.LoadXml( xml );
						if( soapDoc.DocumentElement != null )
						{
							XmlElement faultStringElement = (XmlElement)soapDoc.SelectSingleNode( "//faultstring" );
							if( faultStringElement != null )
							{
								if( ConfigUtil.PureSoapExceptionMessage() )
								{
									message = getPureSoapExceptionMessage( faultStringElement );
								}
								else
								{
									message = message + "\n\n" + faultStringElement.InnerText;
								}
							}
						}
					}
					catch( Exception exc ){}
				}
			}
			form.ModalMessageList.Add( message );
		}

		private static string getPureSoapExceptionMessage( XmlElement faultStringElement )
		{
			string text = faultStringElement.InnerText.Trim();
			if( text.StartsWith( "System.Web.Services.Protocols.SoapException:" ) )
			{
				int startIndex = "System.Web.Services.Protocols.SoapException:".Length;
				int atIndex = text.IndexOf( " at " );
				if( atIndex > 0 )
				{
					string message = text.Substring( startIndex, atIndex - startIndex );
					return message.Trim();
				}
			}
			return text;
		}

		public static void addInnerExceptionMassage( Form form, string prefix, Exception e )
		{
			if( e.InnerException != null )
			{
				//CID 0145 //2008.10.19 //Begin
				if( e.InnerException is WebException )
				{
					WebException webException = e.InnerException as WebException;
					if( webException.Status.Equals( WebExceptionStatus.ProtocolError ) && webException.Message.IndexOf( "401" ) > 0 )
					{
						if( ConfigUtil.HideWS401Message() )
						{
							return;
						}
					}
				}
				//CID 0145 //2008.10.19 //End
				form.ModalMessageList.Add( prefix + ":\r\n" + e.InnerException.Message );
			}
			else
			{
				form.ModalMessageList.Add( prefix + ":\r\n" + e.Message );
			}	
		}

		public static void updateFieldValue( Form form, string jetId, string value )
		{
			if( form.FieldList != null )
			{
				foreach( Field formField in form.FieldList )
				{
					if( formField.JetId.Equals( jetId ) )
					{
						formField.Value = value;
						break;
					}
				}
			}
		}

		public static void updateFieldValue( Form form, XmlNode node )
		{
			if( form.FieldList != null )
			{
				string jetId = DOMUtil.getNodeJetId( node );
				if( jetId != null )
				{
					foreach( Field formField in form.FieldList )
					{
						if( formField.JetId.Equals( jetId ) )
						{
							formField.Value = DOMUtil.getNodeValue( node );
							break;
						}
					}
				}
			}
		}

		public static bool isUnloadDataObject( Form form, DataObject dataObject )
		{
			foreach( DataObject unloadDataObject in form.UnloadDataObjectList )
			{
				if( unloadDataObject.Equals( dataObject ) )
				{
					return true;
				}
			}
			return false;
		}

		public static void updateFormattingNode( Form form, XmlNode node, string nodeValue )
		{
			if( node == null )
			{
				return;
			}
			DOMUtil.setNodeValue( node, nodeValue );
			/*
			//ScriptCode在BuildFormView之前执行,所以要进行检查.
			bool found = false;
			foreach( XmlNode xmlNode in form.NodeChangedByCodeList )
			{
				if( xmlNode.Equals( node ) )
				{
					found = true;
					break;
				}
			}
			if( !found )
			{
				//所有需要格式花的数据库都已经在提交前传递给页面,重新构造XML不应该再对XML进行修改.
				//但是在因为ValueChange而引发的BuildXMLDocByFieldList时,需要提前进行格式化.见FormValueValueChangeDeformatWorker.
				if( form.ValueChangeId != null )
				{
					DOMUtil.setNodeValue( node, nodeValue );
				}
			}
			*/
		}

		public static string replacePiHref( string piValue, string uri )
		{
			if (piValue.IndexOf("href=") < 0)
			{
				piValue = piValue + " href=\"" + uri + "\"";
			}
			else
			{
				int start = -1;
				string compart = "";
				int index1 = piValue.IndexOf("href=\"");
				int index2 = piValue.IndexOf("href='");
				if( index1 > 0 )
				{
					start = index1;
					compart = "\"";
				}
				if( index2 > 0 )
				{
					start = index2;
					compart = "'";
				}
				if( start > 0 )
				{
					int end = piValue.IndexOf( compart, start + 6 );
					if( end > 0 )
					{
						piValue = piValue.Substring( 0, start ) + "href=" + compart + uri + piValue.Substring( end );
					}
				}
			}
			return piValue;
		}

		public static void formatPiHref( Form form )
		{
			XmlDocument doc = form.XmlDoc;
			XmlNodeList nodeList = doc.ChildNodes;
			foreach (XmlNode node in nodeList)
			{
				if (node is XmlProcessingInstruction)
				{
					XmlProcessingInstruction pi = (XmlProcessingInstruction) node;
					if (pi.Name.Equals("mso-infoPathSolution"))
					{
						pi.Value = FormUtil.replacePiHref( pi.Value, form.Manifest.PublishUrl );
					}
				}
			}
		}

		public static bool checkAfterChangeTable( Form form, XmlNode xmlSiteNode )
		{
			if( form.AfterChangeTable == null )
			{
				form.AfterChangeTable = new Hashtable();
			}
			if( form.AfterChangeTable.ContainsKey( xmlSiteNode ) )
			{
				Int16 count = (Int16)form.AfterChangeTable[ xmlSiteNode ];
				if( count == JetConstant.MAX_LOOP_COUNT )
				{
					return false;
				}
				else
				{
					count ++;
					form.AfterChangeTable[ xmlSiteNode ] = count;
					return true;
				}
			}
			else
			{
				Int16 count = 1;
				form.AfterChangeTable[ xmlSiteNode ] = count;
				return true;
			}
		}

		//表单是否是只读的,这是一个API设置,如果为true,表单中所有视图都将是只读的.这是和视图里定义的只读不同.
		public static bool isReadonly(Form form)
		{
			string isReadonly = (string)form.ParamTable[ JetConstant.XDOC_PARAM_READONLY ];
			if( isReadonly == null )
			{
				return form.JetContext.IsReadonly;
			}
			else
			{
				if( isReadonly.ToLower().Equals( "true" ) )
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}

		//读取是否在客户端定义了ajax_bracket.
		public static string parseAjaxBracket(Form form)
		{
			string ajaxBracket = (string)form.ParamTable[ JetConstant.XDOC_PARAM_AJAX_BRACKET ];
			if( ajaxBracket == null )
			{
				ajaxBracket = "";
			}
			return ajaxBracket;
		}

		//获取ajax_bracket。ajax_bracket主要用于InfoJet EditPart中等xdoc.aspx输出了其它内容到AJAX Response中时，在客户端提取出有效的脚本内容。
		public static string getAjaxBracket(Form form)
		{
			string ajaxBracket = (string)form.ParamTable[ JetConstant.XDOC_PARAM_AJAX_BRACKET ];
			if( ajaxBracket == null )
			{
				ajaxBracket = "";
			}
			if( ajaxBracket.Trim().Length <= 0 )
			{
				return "";
			}
			else
			{
				return "--" + ajaxBracket + "--";
			}
		}

		//判断是否因弹出DataObject登录对话框而使用Rebuild Command。
		public static bool isRebuildCommand( Form form )
		{
			string rebuildCommand = (string)form.ParamTable[ JetConstant.XDOC_PARAM_REBUILD_COMMAND ];
			if( rebuildCommand != null && rebuildCommand.Length > 0 )
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		//是否正在通过模板或现存XML打开表单,但不是因弹出DataObject登录对话框而使用Rebuild Command。
		//主要用于判断是否需要缓存/恢复图片和附件.
		public static bool isOpeningForm( Form form )
		{
			if( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) || form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) )
			{
				if( isRebuildCommand( form ) )
				{
					return false;
				}
				else
				{
					return true;
				}
			}
			return false;
		}

		//CID 0504 //2010.02.25 //Begin
		public static bool isOutOfLimits( ArrayList runnedList, CalculatedField calcField )
		{
			int count = 0;
			foreach( CalculatedField cField in runnedList )
			{
				if( cField.Equals( calcField ) )
				{
					count ++;
					if( count >= JetConstant.MAX_LOOP_COUNT )
					{
						return true;
					}
				}
			}
			return false;
		}
		//CID 0504 //2010.02.25 //End

        //CID 0636 //2010.08.04 //Begin
        public static void checkChangedBase64Node(Form form, XmlNode targetNode)
        {
            //CID 0757 //2011.01.12 //Begin
            if (!DOMUtil.isInDocument(targetNode))
            {
                return;
            }
            //CID 0757 //2011.01.12 //End
            //CID 0410 //2009.09.28 //Begin
            //CID 0861 //2011.04.11 //Begin
            //CID 0757 //2011.01.12 //Begin
            bool isBASE64 = false;
            if (Base64TypeUtil.isBase64Field(form, targetNode))
            {
                isBASE64 = true;
            }
            if (isBASE64)
            {
                if (form.ChangedBase64NodeList == null)
                {
                    form.ChangedBase64NodeList = new ArrayList();
                }
                form.ChangedBase64NodeList.Add(targetNode);
            }
            //CID 0757 //2011.01.12 //End
            //CID 0861 //2011.04.11 //End
            //CID 0410 //2009.09.28 //End
        }
        //CID 0636 //2010.08.04 //End

        //CID 0664 //2010.11.02 //Begin
        public static string getChangedFieldOldValue(Form form)
        {
            if (form.Manifest.FormFieldsCacheEnabled)
            {
                return form.CachedOldValue;
            }
            else
            {
                return form.ParamTable[JetConstant.XDOC_PARAM_OLD_VALUE] as string;
            }
        }
        //CID 0664 //2010.11.02 //End
	}
}